<template>
  <div>
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />

    <van-search
      ref="search"
      shape="round"
      v-model="value"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>

    <van-cell-group>
      <van-cell
        v-for="(item, index) in showList"
        :key="index"
        icon="search"
        @click="
          value = list[index]
          $router.push({ path: '/searchResult', query: { q: list[index] } })
        "
      >
        <template #title>
          <div v-html="item"></div>
        </template>
      </van-cell>
    </van-cell-group>

    <van-cell title="历史记录" />
    <van-cell title="js">
      <template #right-icon>
        <van-icon name="close" class="search-icon" />
      </template>
    </van-cell>
    <van-cell title="javascript">
      <template #right-icon>
        <van-icon name="close" class="search-icon" />
      </template>
    </van-cell>
  </div>
</template>

<script>
import { getSuggestionList } from './home.js'
export default {
  name: 'search',
  data () {
    return {
      value: '',
      list: [],
      timeID: null
    }
  },
  methods: {
    onSearch () {
      // console.log(this.value)
      this.$router.push({ path: '/searchResult', query: { q: this.value } })
    },
    onInput () {
      //   console.log(this.value)
      // 函数防抖
      clearTimeout(this.timeID)
      this.timeID = setTimeout(async () => {
        if (this.value.length == 0) {
          this.list = []
          return
        }
        let res = await getSuggestionList(this.value)
        //   console.log(res);
        this.list = res.data.data.options
      }, 500)
    }
  },
  computed: {
    showList () {
      // 返回这个计算属性的值
      return this.list.map(item => {
        let regexp = new RegExp(this.value, 'ig')
        //   返回每一项调用替换方法的值
        //   返回替换后的值
        return item.replace(
          regexp,
          match => `<span style="color:red">${match}</span>`
        )
      })
    }
  },
  mounted() {
    this.$nextTick(()=>{
      this.$refs.search.focus()
    });
  }
}
</script>

<style></style>
